package com.market.cash.ui.fragment

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.market.cash.R
import com.market.cash.databinding.CashStepCommonBinding
import com.market.cash.http.ApiService.addCommonParams
import com.market.cash.pro.ProFragment
import com.market.cash.ui.activity.StepsActivity
import com.market.cash.ui.adapter.CashRootStepCommonAdapter
import com.market.cash.utils.CashRootDensityUtil
import com.market.cash.utils.decoration.LinearSpacingItemDecoration
import com.market.cash.utils.dialog.CashRootBirthdayDialog
import com.market.cash.utils.dialog.CashRootCommonPopupwindow
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.log.CashRootLog
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/22 14:19
 * @Annotation：认证流程 - 通用
 */
class StepCommonFragment(): ProFragment() {
    lateinit var binding: CashStepCommonBinding
    private var stepItem: JSONObject? = null

    private var commonAdapter: CashRootStepCommonAdapter? = null
    private var mSelectPosition = -1

    //出生日期选择
    private var birthdayDialog: CashRootBirthdayDialog? = null

    constructor(data: JSONObject): this(){
        this.stepItem = data
    }

    override fun getCashRootRootView(inflater: LayoutInflater): View {
        binding = CashStepCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initCashRootView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#00000000"))
        initCommonViews()
    }

    override fun initCashRootListener() {
        //下一步
        binding.btnNext.setOnClickListener {
            if (stepItem == null){
                return@setOnClickListener
            }
            if (!isAllowCommonSubmit()){
                showErrorTipsDialog(getString(R.string.tips_submit_error), stepItem!!.optString("stepTitle"))
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().apply {
                put("path", stepItem!!.optString("apiUrl").replace("/",""))
            }
            for (i in 0..<commonAdapter!!.itemCount){
                val item = commonAdapter!!.getItem(i)
                if (item.has("selectItem")){
                    val selectItem = item.optJSONObject("selectItem")
                    if (selectItem != null){
                        params.put(item.optString("paramName"),selectItem.optString("value"))
                    }
                }
            }
            CashRootLog.e(">>>>>>submit data >>>>>>>$params")
            val act = getAct() as StepsActivity
            act.onCashRootSubmitAction(params)

            addCashRootEventPoint(String.format(CashRootEventType.CLICK.CASHROOT_CLICK_STEP_XX_NEXT, stepItem!!.optString("stepTitle")),"")
        }
    }

    override fun initCashRootData() {
        val dataList = arrayListOf<JSONObject>()
        if (stepItem != null){
            val stepTitle = stepItem!!.optString("showTitle")
            binding.textStepTitle.text = stepTitle
            binding.textStepDes.text = String.format(getString(R.string.step_commom_des),stepTitle)

            val dataArray = stepItem!!.optJSONArray("dataList")
            if (dataArray != null) {
                for (i in 0..<dataArray.length()){
                    dataList.add(dataArray.optJSONObject(i))
                }
            }
        }
        commonAdapter!!.data = dataList
    }

    /**
     * 初始化Views
     */
    private fun initCommonViews(){
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        val topDecoration = CashRootDensityUtil.dp2px(16f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        commonAdapter = CashRootStepCommonAdapter(binding.recyclerView)
        binding.recyclerView.adapter = commonAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        commonAdapter!!.setOnItemChildClickListener { _, childView, position ->
            binding.root.clearFocus()
            mSelectPosition = position
            val item = commonAdapter!!.getItem(position)
            when (item.optString("action")) {
                "DATE_PICK" -> {//时间选择
                    showCashRootBirthDialog()
                }
                "SELECT" -> {//选择
                    val dataList = arrayListOf<JSONObject>()
                    val dataArray = item.optJSONArray("values")
                    if (dataArray != null) {
                        for (i in 0..<dataArray.length()) {
                            dataList.add(dataArray.optJSONObject(i))
                        }
                    }
                    showSelectPopupwindow(childView, dataList)
                }
            }
        }
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        val selectPopup = CashRootCommonPopupwindow(requireContext())
        selectPopup.setWindowWidth(view.width + CashRootDensityUtil.dp2px(10f))
        selectPopup.setSelectItemListener(object : CashRootCommonPopupwindow.IItemClickListener {
            //完成
            override fun onConfirmAction(data: JSONObject?) {
                val item = commonAdapter!!.getItem(mSelectPosition)
                item.put("selectItem",data)
                commonAdapter!!.notifyItemChanged(mSelectPosition)

                if (data != null){
                    val subRemark = "${data!!.optString("value")}$$${data.optString("duration")}"
                    addCashRootEventPoint(String.format(CashRootEventType.CLICK.CASHROOT_CLICK_STEP_XX_SELECT,item.optString("paramName")),subRemark)
                }
            }
            //关闭监听
            override fun onDismissListener() {
            }
        })
        selectPopup.show(view, binding.root)
        selectPopup.setBrandList(dataList)
    }

    /**
     * 选择出生日期
     */
    private fun showCashRootBirthDialog(){
        if (birthdayDialog == null){
            birthdayDialog = CashRootBirthdayDialog(requireContext(),"",object : CashRootBirthdayDialog.IDialogCallback{
                override fun completed(selectDate: JSONObject) {
                    //可根据需要自行截取数据显示
                    val item = commonAdapter!!.getItem(mSelectPosition)
                    val obj = JSONObject()
                    obj.put("title",selectDate.optString("showDate"))
                    obj.put("title_sw",selectDate.optString("showDate"))
                    obj.put("value",selectDate.optString("subDate"))
                    item.put("selectItem",obj)
                    commonAdapter!!.notifyItemChanged(mSelectPosition)

                    val subRemark = "${selectDate.optString("subDate")}$$${selectDate.optString("duration")}"
                    addCashRootEventPoint(String.format(CashRootEventType.CLICK.CASHROOT_CLICK_STEP_XX_SELECT,item.optString("paramName")),subRemark)
                }
            })
        }
        birthdayDialog!!.show()
    }

    /**
     * 通用类型列表
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowCommonSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        for (i in 0..<commonAdapter!!.itemCount){
            val item = commonAdapter!!.getItem(i)
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem") || item.optJSONObject("selectItem")?.optString("value")!!.isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    override fun onStart() {
        super.onStart()
        if (stepItem != null){
            addCashRootEventPoint(String.format(CashRootEventType.PAGE.CASHROOT_PAGE_STEP_COMMON_XX_START,stepItem!!.optString("stepTitle")),"")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (stepItem != null){
            addCashRootEventPoint(String.format(CashRootEventType.PAGE.CASHROOT_PAGE_STEP_COMMON_XX_END,stepItem!!.optString("stepTitle")),"")
        }
    }
}